#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
JWT令牌获取工具 - 简化版

提供简单的JWT令牌获取功能，支持用户注册和登录。
"""

import requests
import json
import time
import os
from typing import Optional


def get_jwt_token(username: str = "testuser", 
                  password: str = "password123",
                  base_url: str = "http://127.0.0.1:5000") -> Optional[str]:
    """获取JWT令牌的简单函数
    
    Args:
        username (str): 用户名，默认为 "testuser"
        password (str): 密码，默认为 "password123"
        base_url (str): API基础URL，默认为 "http://127.0.0.1:5000"
        
    Returns:
        Optional[str]: JWT令牌字符串，失败返回None
    """
    base_url = base_url.rstrip('/')
    login_url = f"{base_url}/api/v1/users/login"
    register_url = f"{base_url}/api/v1/users/register"
    
    # 先尝试登录
    login_data = {
        "username": username,
        "password": password
    }
    
    try:
        response = requests.post(login_url, json=login_data, timeout=10)
        
        if response.status_code == 200:
            result = response.json()
            if result.get('code') == 200:
                token = result.get('data', {}).get('access_token')
                print(f"✅ 用户 {username} 登录成功")
                return token
        
        # 如果登录失败，尝试注册
        print(f"⚠️ 登录失败，尝试注册新用户 (用户: {username})")
        
        register_data = {
            "username": username,
            "password": password,
            "confirm_password": password
        }
        
        response = requests.post(register_url, json=register_data, timeout=10)
        
        if response.status_code == 201:
            result = response.json()
            if result.get('code') == 201:
                token = result.get('data', {}).get('access_token')
                print(f"✅ 用户 {username} 注册成功")
                return token
        
        print(f"❌ 无法获取令牌 (用户: {username})")
        
    except requests.Timeout:
        print("❌ 请求超时，请检查服务器是否正常运行")
    except requests.ConnectionError:
        print("❌ 无法连接到服务器，请检查网络连接")
    except Exception as e:
        print(f"❌ 获取令牌过程中发生错误: {e}")
    
    return None


def test_token():
    """测试令牌获取功能"""
    print("🔧 JWT令牌获取测试")
    print("=" * 40)
    
    # 获取令牌
    token = get_jwt_token()
    
    if token:
        print(f"✅ 成功获取令牌: {token[:50]}...")
        
        # 验证令牌
        try:
            headers = {"Authorization": f"Bearer {token}"}
            response = requests.get(
                "http://127.0.0.1:5000/api/v1/users/profile",
                headers=headers,
                timeout=5
            )
            
            if response.status_code == 200:
                print("✅ 令牌验证成功")
            else:
                print("❌ 令牌验证失败")
        except:
            print("❌ 令牌验证失败")
    else:
        print("❌ 获取令牌失败")
    
    print("\n💡 使用说明:")
    print("1. 确保后端服务器运行在 http://127.0.0.1:5000")
    print("2. 调用 get_jwt_token() 函数获取令牌")
    print("3. 可以自定义用户名、密码和服务器地址")


if __name__ == "__main__":
    test_token()